/**
 * 系统配置
 */
import FileSystem from '@/utils/FileSystem'
const { app } = require('electron').remote

function SystemConfig () {
  var installPath = FileSystem.getInstallPath()
  var configFile = installPath + '\\resources\\config.json'
  var methodFile = installPath + '\\resources\\method.json'
  // var devConfigFile = './config.json'
  this.configData = null
  /**
   * 当前环境是否开发环境
   */
  this.isDev = function () {
    return !app.isPackaged
  }
  /**
   * 获取配置文件地址
   * @returns {string}
   */
  this.getConfigFilePath = function () {
    var filePath = configFile
    /* if (this.isDev()) {
      filePath = devConfigFile
    } */
    return filePath
  }
  /**
   * 获取配置文件地址
   * @returns {string}
   */
  this.getMethodFilePath = function () {
    return methodFile
  }
  /**
   * 获取系统配置
   * @returns {any}
   */
  this.getSystemConfig = function () {
    if (this.configData) {
      return this.configData
    }
    var filePath = this.getConfigFilePath()
    // console.log(filePath)
    var configStr = FileSystem.readFileSync(filePath)
    // SystemLog.info('config file path: ' + filePath + ',config data: ' + configStr)
    if (configStr) {
      this.configData = JSON.parse(configStr)
    } else {
      this.configData = {}
    }
    return this.configData
  }
  /**
   * 获取某项系统配置
   * @param type
   * @returns {*}
   */
  this.getSystemConfigType = function (type) {
    var config = this.getSystemConfig()
    return config[type]
  }
  /**
   * 保存配置文件
   * @param config
   */
  this.saveSystemConfig = function (config) {
    var filePath = this.getConfigFilePath()
    var configStr = JSON.stringify(config, null, "\t")
    FileSystem.writeFileSync(filePath, configStr)
    this.configData = config
  }
  /**
   * 保存某项系统配置
   * @param type
   * @param value
   */
  this.saveSystemConfigType = function (type, value) {
    var config = this.getSystemConfig()
    config[type] = value
    this.saveSystemConfig(config)
    this.configData = config
  }
  /**
   * 获取方法配置
   * @returns {any}
   */
  this.getMethodConfig = function () {
    var filePath = methodFile
    var configStr = FileSystem.readFileSync(methodFile)
    // SystemLog.info('method file path: ' + filePath + ',config data: ' + configStr)
    var configData = []
    if (configStr) {
      configData = JSON.parse(configStr)
    }
    return configData
  }
  this.getMethod = function (methodId) {
    var methods = this.getMethodConfig()
    if (!methods || methods.length === 0) {
      return null
    }
    var defaultMethod = null
    for (var i = 0; i < methods.length; i++) {
      if (methods[i].isDefault) {
        defaultMethod = methods[i]
      }
      if (methods[i].methodId === methodId) {
        return methods[i]
      }
    }
    return defaultMethod
  }
}

export default new SystemConfig()
